//
//  HomeView.swift
//  APIEndPoint
//
//  Created by Alfred on 2021/2/7.
//

import SwiftUI

struct HomeView: View {
    let dic:[String:String] = ["key":"bbb","value":"some"]
    
    
    private var apiService = APIService()
    
    @Environment(\.managedObjectContext) var viewContext
    @FetchRequest(entity: EPdata.entity(), sortDescriptors: [NSSortDescriptor(key: "timeInterval", ascending: false)]) var records: FetchedResults<EPdata>
    
    var lastData:(timeStamp: String, user: UserModel?)? {
        guard records.isEmpty == false, let jsonData = records.first!.jsonData else {
            return ("no history data, fetch data in 5s", nil)
        }
        do {
            let user = try JSONDecoder().decode(UserModel.self, from: jsonData)
            return (records.first!.wrappedTimeInterval, user)
        } catch let err {
            print(err.localizedDescription)
            return ("no history data, fetch data in 5s", nil)
        }
    }
    
    var body: some View {
        NavigationView {
            
            List {
                NavigationLink(destination: RecordingView(),label: {
                    Text("查看历史记录").frame(width: UIScreen.main.bounds.width-50, height: 50, alignment: .trailing)
                })
                Text(lastData?.timeStamp ?? "timeStamp")
                    .listRowBackground(Color(.systemGray2))
                
                CellView(userModel: lastData?.user)
            }
            
            .navigationBarTitle(Text("当前数据"), displayMode: .inline)
            
        }
        
        .onAppear {
            apiService.start()
        }
    }
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView()
    }
}
